<template>
  <div class="kafka-config-manager">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>Kafka 配置管理</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="showAddDialog">添加配置</el-button>
      </div>
      
      <!-- 配置列表 -->
      <el-table :data="kafkaConfigs" style="width: 100%" class="config-table">
        <el-table-column prop="name" label="名称" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="url" label="URL" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="topic" label="Topic" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column label="JSON数据" min-width="180">
          <template slot-scope="scope">
            <el-tooltip :content="scope.row.json || '无JSON数据'" placement="top">
              <span class="json-preview">{{ getJsonPreview(scope.row.json) }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template slot-scope="scope">
            <el-button @click="showEditDialog(scope.row)" type="text" size="small">编辑</el-button>
            <el-button @click="showJsonDialog(scope.row)" type="text" size="small">查看JSON</el-button>
            <el-button @click="deleteConfig(scope.$index)" type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 添加/编辑配置对话框 -->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="60%">
        <el-form :model="form" :rules="rules" ref="form" label-width="100px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入配置名称"></el-input>
          </el-form-item>
          <el-form-item label="URL" prop="url">
            <el-input v-model="form.url" placeholder="请输入Kafka服务器地址"></el-input>
          </el-form-item>
          <el-form-item label="Topic" prop="topic">
            <el-input v-model="form.topic" placeholder="请输入主题名称"></el-input>
          </el-form-item>
          <el-form-item label="JSON数据">
            <el-input
              type="textarea"
              :rows="10"
              placeholder="请输入JSON数据（可选）"
              v-model="form.json">
            </el-input>
            <div class="json-actions">
              <el-button type="primary" size="small" @click="validateJson">验证JSON</el-button>
              <el-button type="success" size="small" @click="formatJson" :disabled="!isValidJson">格式化</el-button>
            </div>
            <div v-if="validationMessage" :class="['validation-message', isValidJson ? 'valid' : 'invalid']">
              {{ validationMessage }}
            </div>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveConfig" :loading="saving">确定</el-button>
        </span>
      </el-dialog>
      
      <!-- JSON查看对话框 -->
      <el-dialog title="JSON数据" :visible.sync="jsonDialogVisible" width="70%">
        <div class="json-viewer">
          <pre v-if="currentJson">{{ formatJsonForDisplay(currentJson) }}</pre>
          <div v-else class="no-json">该配置没有JSON数据</div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="jsonDialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { kafkaConfigApi } from '@/api';

export default {
  name: 'KafkaConfigManager',
  data() {
    return {
      kafkaConfigs: [],
      dialogVisible: false,
      jsonDialogVisible: false,
      dialogTitle: '添加配置',
      editIndex: -1,
      saving: false,
      currentJson: '',
      isValidJson: false,
      validationMessage: '',
      form: {
        name: '',
        url: '',
        topic: '',
        json: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入URL', trigger: 'blur' }
        ],
        topic: [
          { required: true, message: '请输入Topic', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadKafkaConfigs();
  },
  methods: {
    // 加载所有Kafka配置
    loadKafkaConfigs() {
      kafkaConfigApi.listKafkaConfigs().then(response => {
        if (response.code === 0) {
          this.kafkaConfigs = response.data;
        } else {
          this.$message.error(response.message || '加载配置失败');
        }
      }).catch(error => {
        console.error('加载配置失败:', error);
        this.$message.error('加载配置失败，请检查网络连接');
      });
    },
    
    // 显示添加对话框
    showAddDialog() {
      this.dialogTitle = '添加配置';
      this.form = {
        name: '',
        url: '',
        topic: '',
        json: ''
      };
      this.editIndex = -1;
      this.isValidJson = false;
      this.validationMessage = '';
      this.dialogVisible = true;
    },
    
    // 显示编辑对话框
    showEditDialog(row) {
      this.dialogTitle = '编辑配置';
      this.form = { ...row };
      this.editIndex = this.kafkaConfigs.findIndex(config => config.id === row.id);
      this.isValidJson = false;
      this.validationMessage = '';
      if (this.form.json) {
        this.validateJson();
      }
      this.dialogVisible = true;
    },
    
    // 显示JSON查看对话框
    showJsonDialog(row) {
      this.currentJson = row.json;
      this.jsonDialogVisible = true;
    },
    
    // 验证JSON
    validateJson() {
      try {
        if (!this.form.json.trim()) {
          this.validationMessage = 'JSON数据为空';
          this.isValidJson = false;
          return;
        }
        
        JSON.parse(this.form.json);
        this.validationMessage = 'JSON格式有效';
        this.isValidJson = true;
      } catch (e) {
        this.validationMessage = `JSON格式无效: ${e.message}`;
        this.isValidJson = false;
      }
    },
    
    // 格式化JSON
    formatJson() {
      if (this.isValidJson) {
        try {
          const jsonObj = JSON.parse(this.form.json);
          this.form.json = JSON.stringify(jsonObj, null, 2);
          this.$message.success('JSON格式化成功');
        } catch (e) {
          this.$message.error('格式化失败');
        }
      }
    },
    
    // 保存配置
    saveConfig() {
      this.$refs.form.validate(valid => {
        if (valid) {
          // 如果有JSON数据，验证其格式
          if (this.form.json && this.form.json.trim()) {
            try {
              JSON.parse(this.form.json);
            } catch (e) {
              this.$message.error('JSON格式无效，请先验证JSON数据');
              return;
            }
          }
          
          this.saving = true;
          const configData = { ...this.form };
          
          // 如果是编辑现有配置，添加ID
          if (this.editIndex !== -1) {
            configData.id = this.kafkaConfigs[this.editIndex].id;
          }
          
          kafkaConfigApi.saveKafkaConfig(configData).then(response => {
            if (response.code === 0) {
              this.dialogVisible = false;
              this.$message.success(response.message || '配置已保存');
              this.loadKafkaConfigs();
            } else {
              this.$message.error(response.message || '保存配置失败');
            }
          }).catch(error => {
            console.error('保存配置失败:', error);
            this.$message.error('保存配置失败，请检查网络连接');
          }).finally(() => {
            this.saving = false;
          });
        }
      });
    },
    
    // 删除配置
    deleteConfig(index) {
      const config = this.kafkaConfigs[index];
      
      this.$confirm('确认删除此配置?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        kafkaConfigApi.deleteKafkaConfig(config.id).then(response => {
          if (response.code === 0) {
            this.$message.success(response.message || '配置已删除');
            this.loadKafkaConfigs();
          } else {
            this.$message.error(response.message || '删除配置失败');
          }
        }).catch(error => {
          console.error('删除配置失败:', error);
          this.$message.error('删除配置失败，请检查网络连接');
        });
      }).catch(() => {
        // 取消删除
      });
    },
    
    // 获取JSON预览
    getJsonPreview(jsonStr) {
      if (!jsonStr) return '无';
      if (jsonStr.length > 50) {
        return jsonStr.substring(0, 50) + '...';
      }
      return jsonStr;
    },
    
    // 格式化JSON用于显示
    formatJsonForDisplay(jsonStr) {
      if (!jsonStr) return '';
      try {
        const jsonObj = JSON.parse(jsonStr);
        return JSON.stringify(jsonObj, null, 2);
      } catch (e) {
        return jsonStr;
      }
    }
  }
}
</script>

<style scoped>
/* 主容器样式 */
.kafka-config-manager {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #f8f9fa;
  min-height: calc(100vh - 120px);
}

/* 卡片样式 */
.kafka-config-manager .box-card {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 卡片头部样式 */
.kafka-config-manager .box-card .el-card__header {
  background: #f8f9fa;
  color: #495057;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e9ecef;
}

.kafka-config-manager .box-card .el-card__header .clearfix span {
  font-size: 18px;
  font-weight: 500;
}

.kafka-config-manager .box-card .el-card__header .el-button {
  color: #495057;
  border: 1px solid #ced4da;
  border-radius: 4px;
  padding: 6px 12px;
  font-weight: 400;
  background: white;
}

.kafka-config-manager .box-card .el-card__header .el-button:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

/* 卡片内容样式 */
.kafka-config-manager .box-card .el-card__body {
  padding: 20px;
}

/* 表格样式 */
.kafka-config-manager .el-table {
  border-radius: 4px;
  border: 1px solid #dee2e6;
}

.kafka-config-manager .el-table th {
  background: #f8f9fa;
  color: #495057;
  font-weight: 500;
  border-bottom: 1px solid #dee2e6;
  padding: 12px;
}

.kafka-config-manager .el-table td {
  padding: 12px;
  border-bottom: 1px solid #dee2e6;
}

.kafka-config-manager .el-table tbody tr:hover {
  background: #f8f9fa;
}

/* JSON预览样式 */
.json-preview {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  color: #6c757d;
  background: #f8f9fa;
  padding: 4px 8px;
  border-radius: 4px;
  border: 1px solid #dee2e6;
  display: inline-block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 表格操作按钮样式 */
.kafka-config-manager .el-table .el-button--text {
  color: #007bff;
  font-weight: 400;
  padding: 4px 8px;
  margin-right: 8px;
}

.kafka-config-manager .el-table .el-button--text:hover {
  color: #0056b3;
  text-decoration: underline;
}

/* 对话框样式 */
.kafka-config-manager .el-dialog {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.kafka-config-manager .el-dialog__header {
  background: #f8f9fa;
  color: #495057;
  padding: 16px 20px;
  border-bottom: 1px solid #dee2e6;
}

.kafka-config-manager .el-dialog__title {
  color: #495057;
  font-size: 16px;
  font-weight: 500;
}

.kafka-config-manager .el-dialog__headerbtn .el-dialog__close {
  color: #6c757d;
  font-size: 18px;
}

.kafka-config-manager .el-dialog__body {
  padding: 20px;
  background: white;
}

.kafka-config-manager .el-dialog__footer {
  padding: 16px 20px;
  background: #f8f9fa;
  border-top: 1px solid #dee2e6;
}

/* 表单样式 */
.kafka-config-manager .el-form-item__label {
  color: #495057;
  font-weight: 500;
  font-size: 14px;
}

.kafka-config-manager .el-input__inner {
  border: 1px solid #ced4da;
  border-radius: 4px;
  padding: 8px 12px;
  font-size: 14px;
}

.kafka-config-manager .el-input__inner:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.kafka-config-manager .el-input__inner:hover {
  border-color: #adb5bd;
}

/* 文本域样式 */
.kafka-config-manager .el-textarea__inner {
  border: 1px solid #ced4da;
  border-radius: 4px;
  padding: 12px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  resize: vertical;
  min-height: 200px;
}

.kafka-config-manager .el-textarea__inner:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
}

.kafka-config-manager .el-textarea__inner:hover {
  border-color: #adb5bd;
}

/* JSON操作按钮样式 */
.json-actions {
  margin-top: 12px;
  display: flex;
  gap: 8px;
}

.json-actions .el-button {
  border-radius: 4px;
  padding: 6px 12px;
  font-size: 12px;
  font-weight: 400;
}

/* 验证消息样式 */
.validation-message {
  margin-top: 12px;
  padding: 8px 12px;
  border-radius: 4px;
  font-weight: 400;
  font-size: 13px;
  border: 1px solid;
}

.validation-message.valid {
  background: #d4edda;
  color: #155724;
  border-color: #c3e6cb;
}

.validation-message.invalid {
  background: #f8d7da;
  color: #721c24;
  border-color: #f5c6cb;
}

/* JSON查看器样式 */
.json-viewer {
  max-height: 500px;
  overflow-y: auto;
  border: 1px solid #dee2e6;
  border-radius: 4px;
  background: #f8f9fa;
}

.json-viewer pre {
  margin: 0;
  padding: 16px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.5;
  color: #495057;
  background: transparent;
}

.no-json {
  padding: 32px;
  text-align: center;
  color: #6c757d;
  font-size: 14px;
}

/* 按钮样式 */
.kafka-config-manager .el-button {
  border-radius: 4px;
  padding: 8px 16px;
  font-weight: 400;
  font-size: 14px;
  border: 1px solid;
}

.kafka-config-manager .el-button--primary {
  background: #007bff;
  border-color: #007bff;
  color: white;
}

.kafka-config-manager .el-button--primary:hover {
  background: #0056b3;
  border-color: #0056b3;
}

.kafka-config-manager .el-button--success {
  background: #28a745;
  border-color: #28a745;
  color: white;
}

.kafka-config-manager .el-button--success:hover {
  background: #1e7e34;
  border-color: #1e7e34;
}

.kafka-config-manager .el-button--default {
  background: #f8f9fa;
  color: #495057;
  border-color: #ced4da;
}

.kafka-config-manager .el-button--default:hover {
  background: #e9ecef;
  border-color: #adb5bd;
}

.kafka-config-manager .el-button:disabled {
  opacity: 0.65;
}

/* 表格样式优化 */
.kafka-config-manager .config-table {
  min-width: 800px;
}

.kafka-config-manager .config-table .el-table__body-wrapper {
  overflow-x: auto;
}

.kafka-config-manager .config-table .el-table th,
.kafka-config-manager .config-table .el-table td {
  padding: 12px 8px;
  white-space: nowrap;
}

.kafka-config-manager .config-table .json-preview {
  display: inline-block;
  max-width: 150px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .kafka-config-manager {
    padding: 16px;
    margin: 0;
  }
  
  .kafka-config-manager .box-card .el-card__body {
    padding: 16px;
  }
  
  .kafka-config-manager .config-table {
    min-width: 600px;
  }
  
  .kafka-config-manager .el-table td,
  .kafka-config-manager .el-table th {
    padding: 8px 4px;
  }
  
  .kafka-config-manager .el-dialog {
    width: 95% !important;
    margin: 5vh auto;
  }
  
  .json-actions {
    flex-direction: column;
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .kafka-config-manager .config-table {
    min-width: 500px;
  }
  
  .kafka-config-manager .config-table .json-preview {
    max-width: 100px;
  }
}

/* 滚动条样式 */
.kafka-config-manager .el-textarea__inner::-webkit-scrollbar,
.json-viewer::-webkit-scrollbar {
  width: 6px;
}

.kafka-config-manager .el-textarea__inner::-webkit-scrollbar-track,
.json-viewer::-webkit-scrollbar-track {
  background: #f8f9fa;
}

.kafka-config-manager .el-textarea__inner::-webkit-scrollbar-thumb,
.json-viewer::-webkit-scrollbar-thumb {
  background: #ced4da;
  border-radius: 3px;
}

.kafka-config-manager .el-textarea__inner::-webkit-scrollbar-thumb:hover,
.json-viewer::-webkit-scrollbar-thumb:hover {
  background: #adb5bd;
}
</style>